package com.pzhu.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzhu.dormitory.dao.UserRoleRelationDao;
import com.pzhu.dormitory.entity.UserRoleRelationEntity;
import com.pzhu.dormitory.service.UserRoleRelationService;
import com.pzhu.dormitory.utils.PageUtils;
import com.pzhu.dormitory.utils.Query;
import com.pzhu.dormitory.vo.UserRolesGrantVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("userRoleRelationService")
public class UserRoleRelationServiceImpl extends ServiceImpl<UserRoleRelationDao, UserRoleRelationEntity> implements UserRoleRelationService {

    @Override
    public PageUtils<UserRoleRelationEntity> queryPage(Map<String, Object> params) {
        IPage<UserRoleRelationEntity> page = this.page(
                new Query<UserRoleRelationEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils<>(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGrantRole(UserRolesGrantVo userRolesGrantVo) {
        this.remove(new LambdaQueryWrapper<UserRoleRelationEntity>().eq(UserRoleRelationEntity::getUserId, userRolesGrantVo.getUserId()));
        List<UserRoleRelationEntity> userRoleRelationEntityList = userRolesGrantVo.getRoleIds().stream().map(roleId -> {
            UserRoleRelationEntity entity = new UserRoleRelationEntity();
            entity.setUserId(userRolesGrantVo.getUserId());
            entity.setRoleId(roleId);
            return entity;
        }).collect(Collectors.toList());
        this.saveBatch(userRoleRelationEntityList);
    }

}
